package com.oliet.security;

import cn.hutool.json.JSONUtil;
import com.oliet.common.result.CommonResponse;
import com.oliet.common.vo.permission.PermissionTreeNodeVO;
import com.oliet.service.UsersService;
import com.oliet.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author jiaZhenpeng
 * @Title: LoginSuccessHandler
 * @Package com.oliet.security
 * @Description: 登录成功处理器
 * @date 2023-11-28 13:11
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private final JwtUtils jwtUtils;
    @Autowired
    private UsersService usersService;

    public LoginSuccessHandler(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        // 生成JWT，并放置到请求头中
        String jwt = jwtUtils.generateToken(auth.getName(),auth.getPrincipal());
        response.setHeader(jwtUtils.getHeader(), jwt);
        //查询当前登录用户权限数据
        List<PermissionTreeNodeVO> permissionTree = this.usersService.getPermissionTreeByUsername(auth.getName());
        CommonResponse result = CommonResponse.data(permissionTree);
        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }


}
